package com.hzsparrow.business.base.service;

import com.hzsparrow.business.base.contant.LoginUserEnum;
import com.hzsparrow.business.base.entity.HzsRole;
import com.hzsparrow.business.base.entity.HzsUser;
import com.hzsparrow.business.base.vo.LoginVO;
import com.hzsparrow.framework.model.result.ResultDTO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

@Service
@Slf4j
public class LoginService {

    @Autowired
    private HzsUserService hzsUserService;

    /**
     * 登录
     *
     * @param request
     * @param account
     * @param password
     * @param verifyCode
     * @return
     */
    public ResultDTO<LoginVO> login(HttpServletRequest request, String account, String password, String verifyCode) {
        String sessionVerifyCode = (String) request.getSession().getAttribute(LoginUserEnum.SESSION_VERIFY_CODE.getFlag());
        if (StringUtils.isNotBlank(sessionVerifyCode) && !StringUtils.equals(sessionVerifyCode.toLowerCase(), verifyCode.toLowerCase())) {
            return ResultDTO.getDataFaild(200, "验证码错误！", null);
        }
        String entryPassword = hzsUserService.getEntryPassword(account, password);
        Subject userSubject = SecurityUtils.getSubject();
        UsernamePasswordToken token = new UsernamePasswordToken(account, entryPassword);
        try {
            userSubject.login(token);
        } catch (UnknownAccountException e) {
            ResultDTO.getDataFaild(403, e.getMessage(), null);
        } catch (ExcessiveAttemptsException e) {
            ResultDTO.getDataFaild(400, "操作频繁，请稍后再试！", null);
        } catch (AccountException e) {
            ResultDTO.getDataFaild(403, e.getMessage(), null);
        } catch (IncorrectCredentialsException e) {
            ResultDTO.getDataFaild(403, "密码错误！", null);
        } catch (Exception e) {
            e.printStackTrace();
            ResultDTO.getDataFaild(403, "登录失败！", null);
        }
        return ResultDTO.getDataSuccess((LoginVO) userSubject.getPrincipal());

    }
}
